<?php

namespace app\admin\model;

use think\db\exception\DbException;
use think\facade\Log;
use think\Model;
use think\model\relation\HasOne;

/**
 * RechargeOrder
 * @controllerUrl 'rechargeOrder'
 * @property int id
 * @property string transaction_id
 * @property int recharge_id
 * @property int order_sn
 * @property int user_id
 * @property float price
 * @property float give_price
 * @property int integral
 * @property int status
 * @property int createtime
 * @property int pay_time
 * @property User user
 */
class RechargeOrder extends Model
{
    // 表名
    protected $name = 'recharge_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $dateFormat = 'Y-m-d H:i:s';

    protected $type = [
        'pay_time' => 'timestamp:Y-m-d H:i:s',
    ];

    /**
     * 获取唯一订单号
     * @return string
     * @throws DbException
     */
    public function getOrderSn(): string
    {
        try {
            [$micro, $time] = explode(' ', microtime());
            $micro = explode('.', sprintf('%.6f', $micro));
            $micro = $micro[1];
        } catch (\Exception $e) {
            $micro = rand(100000, 999999);
        }
        $orderSn = date('YmdHis') . $micro . rand(1000, 9999);
        $hasSn = $this->where('order_sn', $orderSn)->count();
        if ($hasSn > 0) {
            return $this->getOrderSn();
        }
        return $orderSn;
    }

    public function getUserIdAttr($value, $row)
    {
        return !$value ? '' : $value;
    }

    public function user(): HasOne
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    public function paySuccess($message): bool
    {
        try {
            $order = $this->with(['user'])->where('order_sn', $message['out_trade_no'])->find();
            if (!$order) {
                Log::error($message['out_trade_no'] . '不存在');
                return false;
            }
            if ($order->status > 0) {
                Log::error($message['out_trade_no'] . '已支付');
                return false;
            }
            $this->startTrans();
            // 订单设为已支付
            $order->pay_time = time();
            $order->status = 1;
            $order->transaction_id = $message['transaction_id'];
            // 用户支付次数和支付金额
            if (!$order->user) {
                Log::error('用户' . $order->user_id . '不存在');
                return false;
            }
            $recharge = Recharge::where('id', $order->recharge_id)->find();
            UserMoneyLog::create([
                'user_id' => $order->user_id,
                'money' => $recharge->recharge_price,
                'memo' => '充值',
            ]);
            UserMoneyLog::create([
                'user_id' => $order->user_id,
                'money' => $recharge->give_price,
                'memo' => '充值赠送',
            ]);
            UserScoreLog::create([
                'user_id' => $order->user_id,
                'score' => $recharge->integral,
                'memo' => '充值赠送',
            ]);
            $order->save();
            $this->commit();
            return true;
        } catch (\Exception $e) {
            Log::error($e->getFile() . ':' . $e->getLine() . '=>' . $e->getMessage());
            Log::error($e->getTraceAsString());
            return false;
        }
    }
}